unit services;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
  ExtCtrls, StdCtrls, Spin, EditBtn, Buttons, clientdb, db;

type

  { TServiceForm }

  TServiceForm = class(TForm)
    ButtonPanel: TPanel;
    CancelButton: TBitBtn;
    ChargeBox: TLabeledEdit;
    DeptCombo: TComboBox;
    DiscountComboBox: TComboBox;
    Label3: TLabel;
    Label4: TLabel;
    MainPanel: TPanel;
    NameBox: TLabeledEdit;
    OKButton: TBitBtn;
    procedure FormCreate(Sender: TObject);
    procedure GetDepartments;
    procedure GetDiscounts;
    procedure OKButtonClick(Sender: TObject);
  private
    CurrentService: integer;
    FErrorMessage: string;
    FOnError: TDBErrorEvent;
    function ValidateInput: Boolean;
    { private declarations }
  public
    { public declarations }
    function ShowNew: TModalResult;
    function ShowEdit(productid: integer) : TModalResult;
    property OnError: TDBErrorEvent read FOnError write FOnError;
    property ErrorMessage: string read FErrorMessage;
  end;

var
  ServiceForm: TServiceForm;

implementation

uses fpstructs, fposUtils, main;

{ TServiceForm }

procedure TServiceForm.FormCreate(Sender: TObject);
begin
  GetDepartments;
  GetDiscounts;
end;

procedure TServiceForm.GetDepartments;
var
  r: integer;
begin
  r := 1;
  try
    MainDB.SQL := 'SELECT id, name FROM Departments ORDER BY name';
    MainDB.Open;
    MainDB.First;
    if MainDB.State=dsBrowse then
        while not MainDB.EOF do
          begin
            DeptCombo.Items.AddObject(MainDB.FieldByName('name').AsString,
                                   TObject(MainDB.FieldByName('id').AsInteger));
            MainDB.Next;
          end;
  finally
    MainDB.Close;
  end;
end;

procedure TServiceForm.GetDiscounts;
var
    r: integer;
begin
    r := 1;
    try
      MainDB.SQL := 'SELECT discountID, description FROM Discounts ORDER BY description';
      MainDB.Open;
      MainDB.First;
      if MainDB.State=dsBrowse then
          while not MainDB.EOF do
            begin
              DiscountComboBox.Items.AddObject(MainDB.FieldByName('description').AsString,
                                     TObject(MainDB.FieldByName('discountID').AsInteger));
              MainDB.Next;
            end;
    finally
      MainDB.Close;
    end;
end;

procedure TServiceForm.OKButtonClick(Sender: TObject);
begin
  if ValidateInput then ModalResult := mrOK;
end;

function TServiceForm.ValidateInput: Boolean;
begin
Result := false;
NameBox.Text := Trim(NameBox.Text);
if Length(NameBox.Text) < 3 then
   begin
     ShowMessage('Product name must be at least 3 characters in length');
     NameBox.SetFocus;
     exit;
   end
else if DeptCombo.ItemIndex < 0 then
   begin
     ShowMessage('Select a valid sales department');
     DeptCombo.SetFocus;
     exit;
   end
else if not IsValidCost(ChargeBox.Text) then
   begin
     ShowMessage('Enter a valid charge');
     ChargeBox.SetFocus;
     exit;
   end
else Result := true;
end;

function TServiceForm.ShowNew: TModalResult;
begin
  Result := ShowModal;
  if Result = mrOK then
     try
       if not MainDB.ExecRemoteSQL('INSERT INTO Products (productid, saleprice, name, dept) '
                  + 'VALUES ((select productid+1 FROM Products WHERE productid<1000 ORDER BY productid DESC LIMIT 1), '
                  +  ChargeBox.Text
                  + ',''' + EscapeQuotes( NameBox.Text )
                  + ''',' + IntToStr(Integer(DeptCombo.Items.Objects[DeptCombo.ItemIndex]))
                  + ');', True)
          then
            begin
              FErrorMessage := 'Error when adding new service';
              if Assigned(FOnError) then FOnError(FErrorMessage);
              Result := mrCancel;
            end;
     finally
       MainDB.Close;
     end;
end;

function TServiceForm.ShowEdit(productid: integer): TModalResult;
var
  query: String;
  discount: Integer;
  x: Integer;
  discontinuedflag: Char;
begin
  try
    query := 'SELECT products.name AS name, saleprice, discount, Departments.name AS dept'
           + ' FROM products, departments WHERE products.productid=' + IntToStr(productid)
           + ' AND Departments.id=products.dept;';
    {$IFDEF DEBUG} writeln(query); {$ENDIF}
    MainDB.SQL := query;
    MainDB.Open;
      begin
        CurrentService := productid;
        NameBox.Text := MainDB.FieldByName('name').AsString;
        ChargeBox.Text := FormatFloat('0.00', MainDB.FieldByName('saleprice').AsFloat);
        DeptCombo.ItemIndex := DeptCombo.Items.IndexOf( MainDB.FieldByName('dept').AsString);
        discount := MainDB.FieldByName('discount').AsInteger;
        if discount>0 then
          for x := 1 to DiscountComboBox.Items.Count-1 do
              if Integer(DiscountComboBox.Items.Objects[x])=discount
                 then DiscountComboBox.ItemIndex := x;
      end;
   Result := ShowModal;
   if Result = mrOk then
      begin
        discount := 0;
        if DiscountComboBox.ItemIndex>0
           then discount := Integer(DiscountComboBox.Items.Objects[DiscountComboBox.ItemIndex]);
        query := 'UPDATE products SET name=''' + EscapeQuotes( NameBox.Text )
                 + ''', saleprice=' + ChargeBox.Text
                 + ', dept=' + IntToStr(Integer(DeptCombo.Items.Objects[DeptCombo.ItemIndex]))
                 + ', discount=' + IntToStr(discount)
                 + ' WHERE productid=' + IntToStr(CurrentService) + ';';
        if not MainDB.ExecRemoteSQL( query, true) then
          begin
            {$IFDEF DEBUG} writeln('Error modifying service'); {$ENDIF}
            FErrorMessage := 'Error modifying service';
            if Assigned(FOnError) then FOnError(FErrorMessage);
            Result := mrCancel;
          end;
      end;
  finally
   MainDB.Close;
 end;
end;

initialization
  {$I services.lrs}

end.

